package tw.miku.protocol.xml;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import tw.miku.ServerParam;
import tw.miku.TestMina;
import tw.miku.model.Group;
import tw.miku.model.User;

public class LoginHandler implements IMessageHandler
{
	private static Logger logger = Logger.getLogger(LoginHandler.class);
	public static final String NAME = "login";

	public LoginHandler()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * <login n="User2" p=""/>
	 */
	@Override
	public void handleData(Element element, IoSession session)
	{
		// TODO Auto-generated method stub
		// logger.info("test:" + element.asXML());
		String name = element.attributeValue("n");
		// String password = element.attributeValue("p");
		Group group = TestMina.getGroup();

		if (group.containUser(name))
		{
			Element loginElement = DocumentHelper.createElement("login");
			loginElement.addAttribute("r", "1");
			session.write(loginElement.asXML());
			return;
		}

		User user = new User();
		user.setId(session.getId());
		user.setName(name);
		// user.set
		user.setSession(session);
		user.setStatus(User.STATUS_LOBBY);

		// return login
		Element loginElement = DocumentHelper.createElement("login");
		loginElement.addAttribute("r", "0");
		loginElement.addAttribute("n", name);
		loginElement.addAttribute("f",
				String.valueOf(ServerParam.MARJOR_VERSION));
		loginElement.addAttribute("s",
				String.valueOf(ServerParam.MINOR_VERSION));
		loginElement.addAttribute("id", String.valueOf(session.getId()));
		loginElement.add(group.getRoomsXmlInfo());
		loginElement.add(group.getUsersXmlInfo());
		user.send(loginElement.asXML());
		group.addUser(user);

		Element onlineElement = DocumentHelper.createElement("ol");
		onlineElement.addAttribute("n", user.getName());
		onlineElement.addAttribute("id", String.valueOf(user.getId()));
		group.sendToAllUser(onlineElement.asXML(), User.STATUS_LOBBY);
	}

}
